<?php

namespace App\Http\Controllers;

use App\Imports\OrganizeUsersImport;
use App\Models\User;
use App\Services\CommonService;
use App\Services\DepartmentService;
use App\Services\OrganizeService;
use App\Services\UserService;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Http\JsonResponse;

/**
 * 组织架构 控制器类
 * Class OrganizeController
 * @package App\Http\Controllers
 */
class OrganizeController extends Controller
{
    public $organizeService;
    public $departmentService;
    public $userService;

    public function __construct(OrganizeService $organizeService, DepartmentService $departmentService, UserService $userService)
    {
        parent::__construct();
        $this->userService       = $userService;
        $this->organizeService   = $organizeService;
        $this->departmentService = $departmentService;
    }

    /**
     * 展示组织架构
     *
     * @return JsonResponse
     * @author: lxk
     * @date: 2024/3/20 9:52
     */
    public function index() : JsonResponse
    {
        $list = $this->organizeService->organize();

        return $this->success($list);
    }

    /**
     * 删除组织架构节点
     *
     * @param Request $request
     * @return JsonResponse
     * @author: lxk
     * @date: 2024/3/20 9:53
     */
    public function delNode(Request $request) : JsonResponse
    {
        $type  = $request->input('type');
        $id    = $request->input('id');

        $this->organizeService->delNode($type, $id);

        return $this->success('', '删除成功！');
    }

    /**
     * 在组织架构里面 编辑项目、参见单位、部门，因为在这里编辑只能修改名称 title，三个编辑统一
     *
     * @param Request $request
     * @return JsonResponse
     * @author: lxk
     * @date: 2024/3/20 9:53
     */
    public function editTitle(Request $request) : JsonResponse
    {
        $type  = $request->input('type'); //类型  project 项目，part_company 参见单位
        $id    = $request->input('id');
        $title = $request->input('title');

        if (!$this->organizeService->editTitle($type, $id, $title)) {
            return $this->error('编辑失败！');
        }
        return $this->success('', '编辑成功！');
    }

    /**
     * 返回组织架构下的用户 公司、项目、部门、参见单位，有且仅有一个不为 0
     *
     * @param Request $request
     * @return JsonResponse
     * @author: lxk
     * @date: 2024/3/20 9:54
     */
    public function users(Request $request) : JsonResponse
    {
        $perPage = $request->input('per_page') ?: $this->limit;

        $companyId     = company_id();
        $projectId     = $request->input('project_id');
        $partCompanyId = $request->input('part_company_id');
        $departmentId  = $request->input('department_id');
        $keyword       = $request->input('keyword', '');

        $users = $this->organizeService->getUsers($perPage, $companyId, $projectId, $departmentId, $partCompanyId, $keyword);

        return $this->success($users);
    }

    /**
     * 组织架构添加单个用户 手机号先搜索，找到后即可添加
     *
     * @param Request $request
     * @return JsonResponse
     * @author: lxk
     * @date: 2024/3/20 9:55
     */
    public function addOneUser(Request $request) : JsonResponse
    {
        $userId        = $request->input('user_id'); //一定存在
        $companyId     = $request->input('company_id'); //一定存在
        $projectId     = $request->input('project_id');
        $partCompanyId = $request->input('part_company_id');
        $departmentId  = $request->input('department_id');

        if (empty($userId) || empty($companyId)) {
            return $this->error('参数错误！');
        }
        if (is_super_admin($userId)) {
            return $this->error('超管不能被添加！');
        }
        OrganizeService::addCompanyUser($companyId, $userId);

        if ($projectId) { //如果指定项目
            OrganizeService::addProjectUser($projectId, $userId);
        }
        if ($partCompanyId) { //如果指定了参见单位
            OrganizeService::addPartCompanyUser($partCompanyId, $userId);
        }
        if ($departmentId) { //如果指定了部门
            OrganizeService::addDepartmentUser($departmentId, $userId);
        }
        $userInfo = User::query()->find($userId);
        CommonService::addActionLog('组织架构添加单个用户', "用户:{$userInfo->nickname}");

        return $this->success('', '添加成功！');
    }

    /**
     * 修改组织架构用户状态
     *
     * @param Request $request
     * @return JsonResponse
     * @author: lxk
     * @date: 2024/3/20 9:55
     */
    public function changeUserStatus(Request $request) : JsonResponse
    {
        $userId        = $request->input('user_id'); //一定存在
        $companyId     = $request->input('company_id');
        $projectId     = $request->input('project_id');
        $partCompanyId = $request->input('part_company_id');
        $status        = $request->input('status');

        $event = '组织架构禁用单个用户';
        if ($companyId) {
            $event = '组织架构禁用单个公司用户';
            OrganizeService::changeCompanyUser($companyId, $userId, $status);
        }
        if ($projectId) {
            $event = '组织架构禁用单个项目用户';
            OrganizeService::changeProjectUser($projectId, $userId, $status);
        }
        if ($partCompanyId) {
            $event = '组织架构禁用单个参见单位用户';
            OrganizeService::changePartCompanyUser($partCompanyId, $userId, $status);
        }
        $userInfo = User::query()->find($userId);
        CommonService::addActionLog($event, "用户:{$userInfo->nickname}");

        return $this->success('', '操作成功！');
    }

    /**
     * 用户导入组织架构
     *
     * @param Request $request
     * @return JsonResponse
     * @author: lxk
     * @date: 2024/3/20 9:55
     */
    public function userImport(Request $request) : JsonResponse
    {
        if (!$request->input('company_id')) {
            return $this->error('请指定公司');
        }
        if (!$request->input('company_id')) {
            return $this->error('请指定公司');
        }
        $this->userService->isFileValid($request);

        $importCountKey = get_rand_str('import_user_count');
        redis()->setex($importCountKey, 120, 0); //导入一个卷内excel，用时最大2分钟

        Excel::import(new OrganizeUsersImport($importCountKey), $request->file('file'));

        $count = redis()->get($importCountKey) ?: 0;

        CommonService::addActionLog('用户导入组织架构');

        return $this->success('', "成功导入【{$count}】个用户");
    }

    /**
     * 删除组织架构用户 (从组织架构里面删除，users表不删除)
     *
     * @param Request $request
     * @return JsonResponse
     * @author: lxk
     * @date: 2024/3/20 9:56
     */
    public function delUser(Request $request) : JsonResponse
    {
        $userIds       = $request->input('user_ids'); //肯定有值
        $companyId     = $request->input('company_id'); //肯定有值
        $projectId     = $request->input('project_id');
        $departmentId  = $request->input('department_id');
        $partCompanyId = $request->input('part_company_id');

        $this->organizeService->delUser($userIds, $companyId, $projectId, $departmentId, $partCompanyId);

        return $this->success('', '删除成功!');
    }
}
